package com.quanyan.user.service.admin.impl;

import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.AppVersionInfoMapper;
import com.quanyan.user.model.db.TbUser;
import com.quanyan.user.model.vo.request.admin.ReqAppVersionInfo;
import com.quanyan.user.model.vo.response.admin.RespAppVersionInfo;
import com.quanyan.user.model.vo.response.admin.RespUserComplainant;
import com.quanyan.user.service.admin.AppVersionInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by hua on 2016/9/18.
 */
@Service
public class AppVersionInfoServiceImpl implements AppVersionInfoService {
    private final static Logger logger = LoggerFactory.getLogger(AppVersionInfoServiceImpl.class);

    @Autowired
    private AppVersionInfoMapper appVersionInfoMapper;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Override
    public List<RespAppVersionInfo> getAppVersionList() {
        List<RespAppVersionInfo> appVersionInfos = null;
        try {
            appVersionInfos = appVersionInfoMapper.selectAppVersionList();
        } catch (Exception e) {
           logger.error("获取App版本信息失败！");
        }
        return appVersionInfos;
    }

    @Override
    public void insertAppVersion(ReqAppVersionInfo appVersionInfo) {
        try {
            int result = appVersionInfoMapper.insertAppVersionInfo(appVersionInfo);
            if (result == 1) {
                myRedisTemplate.delteKey(UserConstants.getVersionInfoKey());   //考虑到版本的兼容性
            }
            if (result == 1 && appVersionInfo.getOs() == 1 ){  //表示ios
                myRedisTemplate.delteKey("redis_version_info_1");
            }
            if (result == 1 && appVersionInfo.getOs() == 2) { //表示Andriod
                myRedisTemplate.delteKey("redis_version_info_2");
            }
        } catch (Exception e) {
            logger.error("更新App版本信息失败！");
        }
    }

    @Override
    public PageObj<List<RespAppVersionInfo>> getAppVersionListByOS(int os,int appType, int pageNo, int pageSize) {
        List<RespAppVersionInfo> appVersionInfos = null;
        int total = 0;
        try {
            appVersionInfos = appVersionInfoMapper.selectAppVersionListByOS(os,appType,pageNo*pageSize,pageSize);

            total = appVersionInfoMapper.selectAppVersionCountByOS(os,appType);
        } catch (Exception e) {
            logger.error("获取App版本更新历史记录列表失败！", e.getMessage());
        }
        return PageObj.create(total, pageNo, pageSize, appVersionInfos);
    }
}
